package cn.zzuisa.bluebox.base.strutils;

import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang3.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonJsonUtil {
	private static Lock lock = new ReentrantLock();
	static ObjectMapper objectMapper;
	static {
		objectMapper = new ObjectMapper();
	}
	public static <T> String toJson(T o) {
		try {
			if(o == null) {
				return null;
			}
			lock.lock();
			String json = objectMapper.writeValueAsString(o);
			json.toCharArray()[0] = ' ';
			json.toCharArray()[json.length() - 1] = ' ';
			return String.valueOf(json).trim().replaceAll("\\\\", "");
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public static <T> T toObject(String str, Class<?> clazz) {
		try {
			if(StringUtils.isEmpty(str) || clazz == null) {
				return null;
			}
			lock.lock();
			return (T)objectMapper.readValue(str, clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			lock.unlock();
		}
		return null;
	}
	public static void main(String[] args) {
	}
}
